package com.Bigbluebook.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.Bigbluebook.R;
import com.Bigbluebook.Service.MessageApiService;
import com.Bigbluebook.adapter.ChatMessageAdapter;
import com.Bigbluebook.adapter.MessageAdapter;
import com.Bigbluebook.entity.Message;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ConversationActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ChatMessageAdapter adapter;
    private EditText inputText;
    private Button sendButton;
    private List<Message> messages;
    private Long receiverId; // 假设你已经有了接收者的ID
    private int userid;
    private MessageApiService messageApiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversation);
        messageApiService = new MessageApiService();
        recyclerView = findViewById(R.id.msg_recycler_view);
        inputText = findViewById(R.id.input_text);
        sendButton = findViewById(R.id.send);
        SharedPreferences sharedPreferences = this.getSharedPreferences("user_info", Context.MODE_PRIVATE);
        userid = sharedPreferences.getInt("userid", -1); // 确保使用正确的类型
        Intent intent = getIntent();
        receiverId = intent.getLongExtra("userId", -1);
        messages = new ArrayList<>();
        adapter = new ChatMessageAdapter(messages);
        adapter.setUserId((long) userid);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendMessage();
            }
        });

        // 加载历史消息
        loadMessages((long)userid,(long)receiverId);
    }

    private void sendMessage() {
        String messageContent = inputText.getText().toString();
        if (!messageContent.isEmpty()) {
            // 创建消息对象并添加到列表
            Message message = new Message();
            message.setContent(messageContent);
            message.setSenderId((long) userid);
            message.setReceiverId(receiverId);
            messages.add(message);
            adapter.notifyDataSetChanged();

            // 发送消息到服务器
            sendToServer(message);

            // 清空输入框并滚动到底部
            inputText.setText("");
            recyclerView.smoothScrollToPosition(messages.size() - 1);
        }
    }

    private void sendToServer(Message message) {
        // 使用 Retrofit 发送消息
        messageApiService.sendMessage(message.getSenderId(), message.getReceiverId(), message.getContent(), new Callback<Message>() {
            @Override
            public void onResponse(Call<Message> call, Response<Message> response) {
                if (response.isSuccessful()) {
                    // 更新消息状态
                    Message sentMessage = response.body();
                    if (!messages.contains(sentMessage)) {
                        messages.add(0, sentMessage); // 将新消息添加到列表的开始位置
                        adapter.notifyDataSetChanged(); // 通知适配器数据有变化
                    }
                } else {
                    // 处理错误情况
                    Log.e("消息发送", response.toString());
                }
            }

            @Override
            public void onFailure(Call<Message> call, Throwable t) {
                // 处理请求失败情况
                Log.e("消息发送", "网络请求失败: " + t.getMessage());
                Toast.makeText(ConversationActivity.this, "发送消息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
    private void loadMessages(Long myId, Long otherUserId) {
        // 加载对话消息
        messageApiService.listMessagesBySenderAndReceiverId(myId, otherUserId, new Callback<List<Message>>() {
            @Override
            public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
                if (response.isSuccessful()) {
                    List<Message> conversationMessages = response.body();
                    // 更新消息列表
                    messages.clear();
                    messages.addAll(conversationMessages);
                    adapter.notifyDataSetChanged();
                    Log.d("ConversationActivity", "Loaded conversation messages: " + messages.size());
                } else {
                    // 处理错误情况
                    Log.e("消息加载", response.toString());
                }
            }

            @Override
            public void onFailure(Call<List<Message>> call, Throwable t) {
                // 处理请求失败情况
                Log.e("消息加载", "网络请求失败: " + t.getMessage());
                Toast.makeText(ConversationActivity.this, "加载消息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

